#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/ledc.h"

#define LED1_PIN 4
#define LED2_PIN 5
#define LED3_PIN 15
#define BUTTON_PIN 14

void app_main(void)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_HIGH_SPEED_MODE,
        .timer_num = LEDC_TIMER_0,
        .duty_resolution = LEDC_TIMER_13_BIT,
        .freq_hz = 5000,
        .clk_cfg = LEDC_AUTO_CLK,
    };

    ledc_channel_config_t ledc_channel0 = {
        .channel = LEDC_CHANNEL_0,
        .duty = 0,
        .gpio_num = LED1_PIN,
        .speed_mode = LEDC_HIGH_SPEED_MODE,
        .hpoint = 0,
        .timer_sel = LEDC_TIMER_0,
    };

    ledc_channel_config_t ledc_channel1 = {
        .channel = LEDC_CHANNEL_1,
        .duty = 0,
        .gpio_num = LED2_PIN,
        .speed_mode = LEDC_HIGH_SPEED_MODE,
        .hpoint = 0,
        .timer_sel = LEDC_TIMER_0,
    };

    ledc_channel_config_t ledc_channel2 = {
        .channel = LEDC_CHANNEL_2,
        .duty = 0,
        .gpio_num = LED3_PIN,
        .speed_mode = LEDC_HIGH_SPEED_MODE,
        .hpoint = 0,
        .timer_sel = LEDC_TIMER_0,
    };

    ledc_timer_config(&ledc_timer);

    ledc_channel_config(&ledc_channel0);
    ledc_channel_config(&ledc_channel1);
    ledc_channel_config(&ledc_channel2);

    gpio_config_t btn;
    btn.pin_bit_mask = 1 << BUTTON_PIN;
    btn.mode = GPIO_MODE_INPUT;
    btn.pull_up_en = GPIO_PULLUP_ENABLE;
    btn.pull_down_en = GPIO_PULLDOWN_DISABLE;
    btn.intr_type = GPIO_INTR_DISABLE;
    gpio_config(&btn);

    int sw = 0;
    int value = 0;

    while (1)
    {
        if (gpio_get_level(BUTTON_PIN) == 0)
        {
            vTaskDelay(pdMS_TO_TICKS(10));
            if (gpio_get_level(BUTTON_PIN) == 0)
            {
                while (gpio_get_level(BUTTON_PIN) == 0)
                    ;
                sw = !sw;
            }
        }
        if (sw)
        {
            value = value + 10;
        }
        else
        {
            value = value - 10;
        }
        if (value > 8192)
        {
            value = 8192;
        }
        if (value < 0)
        {
            value = 0;
        }
        
        ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, value);
        ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1, value);
        ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2, value);
        ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0);
        ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_1);
        ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_2);
        
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}
